import axios from 'axios';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from "../router"
import {Message} from 'element-ui'

export const request = createInctance();

const errorHandle = (status, msg) => {
  switch (status) {
    //提示信息
    case 0:
      Message(msg);
      break;

    //登录过期
    case 1000:
    case 1001:
      Message('登录失效或已过期');
      window.sessionStorage.clear();
      router.replace({path: '/login', query: {redirect: router.currentRoute.fullPath}});
      break;

    case 404:
      Message(msg);
      break;

    case 500:
      Message(msg);
      break;

    default:
      console.log(msg);
  }
}

function createInctance() {
  const instance = axios.create({
    baseURL: '/api',
    timeout: 5000,
    headers: {
      //'Content-Type': 'application/x-www-form-urlencoded'
    },
  })

  //添加请求拦截器
  instance.interceptors.request.use(handerRequest);
  //添加响应拦截器
  instance.interceptors.response.use(handerResponse, error => {
    errorHandle(error.response.status, error.response.data.message);
    return Promise.reject(error);
  });

  return instance;
}

//拦截请求器
function handerRequest(config) {
  //开启加载
  NProgress.start();

  config.headers.Authorization = window.sessionStorage.getItem('user-token');

  return config;
}

//添加响应拦截器
function handerResponse(response) {
  errorHandle(response.status == 200 ? response.data.code : response.status, response.data.message || response.data.msg);

  //转换一下
  response.data.code == 1 && (response.data.code = 200);
  //关闭加载框
  NProgress.done();

  console.log(response.data)
  return response.data;
}
